<template>
  <div class="p-3">
    <a-card class="w-full" style="height: 830px" :bordered="false">
      <a-form layout="inline">
        <a-form-item label="维护时间">
          <a-range-picker v-model:value="searchForm.time" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="机构编号">
          <a-tree-select
            v-model:value="searchForm.comId"
            tree-node-filter-prop="label"
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="功能模块">
          <a-input
            v-model:value="searchForm.functionName"
            style="width: 200px"
            placeholder="请输入功能模块"
          ></a-input>
        </a-form-item>
        <a-form-item label="操作类型">
          <a-select
            v-model:value="searchForm.operationType"
            style="width: 200px"
            :options="options"
          ></a-select>
        </a-form-item>
        <a-form-item label="修改人">
          <a-tree-select
            v-model:value="searchForm.operator"
            tree-data-simple-mode
            allow-clear
            style="width: 260px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="selectList"
            placeholder="请选择修改人"
            :load-data="onLoadData"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            class="mr-3"
            :icon="h(SearchOutlined)"
            @click="onSearch"
            >查询</a-button
          >
          <a-button type="primary" :icon="h(RedoOutlined)" class="mr-3"
            >重置</a-button
          >
        </a-form-item>
      </a-form>
      <a-table
        :columns="columns"
        :data-source="data"
        bordered
        class="mt-3"
        :pagination="pagination"
      >
        <template #bodyCell="{ column, text }">
          <template v-if="column.dataIndex === 'name'">
            <a>{{ text }}</a>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script lang="ts" setup>
import { h, ref, reactive } from "vue";
import { SearchOutlined, RedoOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { getOperationLog } from "#/api/core/setting";
import { getCompanyTree } from "#/api/core/develop";
import { getOperatorApi } from "#/api/core/statistical";
import dayjs from "dayjs";
const options = [...Array(25)].map((_, i) => ({
  value: (i + 10).toString(36) + (i + 1),
}));
const columns = [
  {
    title: "功能名称",
    dataIndex: "functionName",
    key: "functionName",
    algin: "center",
  },
  {
    title: "操作类型",
    dataIndex: "operationType",
    key: "operationType",
    algin: "center",
  },
  {
    title: "操作人编号",
    dataIndex: "numbers",
    key: "numbers",
    algin: "center",
  },
  {
    title: "操作人",
    dataIndex: "updateName",
    key: "updateName",
    algin: "center",
  },
  {
    title: "维护时间",
    dataIndex: "maintenanceDate",
    key: "maintenanceDate",
    algin: "center",
  },
  {
    title: "操作报文",
    dataIndex: "operationMessage",
    key: "operationMessage",
    algin: "center",
  },
  {
    title: "操作记录",
    dataIndex: "operationRecord",
    key: "operationRecord",
    algin: "center",
  },
];
const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error("获取操作人员列表失败:", error);
      message.error("获取操作人员列表失败");
    });
};
getList();
const selectList = ref([]);
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error("加载子节点失败:", error);
        message.error("加载子节点失败");
        resolve(undefined);
      });
  });
};
const searchForm = reactive({
  time: "",
  numbers: "",
  functionName: "",
  operationType: "",
  comId: undefined,
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    // onSearch();
  },
});
const data = ref([]);
const onSearch = () => {
  const query = {
    time: searchForm.time
      ? dayjs(searchForm.time[0]).format("YYYY-MM-DD") +
        "," +
        dayjs(searchForm.time[1]).format("YYYY-MM-DD")
      : "",
    numbers: searchForm.numbers,
    functionName: searchForm.functionName,
    operationType: searchForm.operationType,
    comId: searchForm.comId,
  };
  console.log(query);
  getOperationLog(pagination.current, pagination.pageSize, query).then(
    (res: any) => {
      console.log(res);
      data.value = res.list;
      pagination.total = res.total;
    }
  );
};
</script>
<style scoped></style>
